//
//  CZComposePictureView.swift
//  CZVVeiBo
//
//  Created by smile on 2017/8/6.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
// cell 间距
private let cellMargin: CGFloat = 5
// 计算cell的宽高
private let cellWH = (CZSCREENW - 20 - cellMargin*2)/3
class CZComposePictureView: UICollectionView {
    
    var closure:(()->())?
    
    // 保存图片
    fileprivate var imageList:[UIImage] = [UIImage]()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        // 创建flowLayout 
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        flowLayout.minimumLineSpacing = cellMargin
        flowLayout.minimumInteritemSpacing = cellMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 提供一个方法供外界使用
    func addImage(image: UIImage){
        // 显示
        isHidden = false
        // 保存到数组中
        imageList.append(image)
        // 刷新配图
        reloadData()
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.white
        // 隐藏
        isHidden = true
        // 注册cell
        register(CZComposePictureViewCell.self, forCellWithReuseIdentifier: "cell")
        dataSource = self
        delegate = self
    }

}

extension CZComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 记录count
        let count = imageList.count
        // 判断如果是0张或者是9张
        if count == 0 || count == 9 {
            return count
        }
        return count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CZComposePictureViewCell
        // 赋值
        // 如果是1-8张 我们需要最后一个cell显示加号cell
        if self.imageList.count == indexPath.item {
            cell.image = nil
        }else{
            cell.image = self.imageList[indexPath.item]
            // 实例化
            cell.closure = {
                // 删除指定元素
                self.imageList.remove(at: indexPath.item)
                // 判断
                if self.imageList.count == 0 {
                    self.isHidden = true
                }
                // 刷新
                self.reloadData()
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        // 监听加号cell点击打开相册
        if self.imageList.count == indexPath.item {
            closure?()
        }
    }
}
